package lee.vioson.remotedata.repositories

import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
import lee.vioson.remotedata.ApiServices
import lee.vioson.remotedata.bean.BannerData
import lee.vioson.remotedata.bean.Book
import lee.vioson.remotedata.bean.HomeData
import lee.vioson.remotedata.database.AppDataBase
import lee.vioson.remotedata.manager.AppConfigManager
import lee.vioson.remotedata.manager.HomeDataManager
import lee.vioson.remotedata.utils.body

/**
 *Author:viosonlee
 *Date:2023/6/3
 *DESCRIPTION:
 */
class HomeRepositoryImpl(
    private val context: Context,
    private val apiServices: ApiServices,
    private val dataBase: AppDataBase
) :
    HomeRepository,
    BaseRepository() {

    override val bannerData: Flow<List<BannerData>> = flow {
        AppConfigManager.INTANCE.getInitAppConfig(context).collect { appConfig ->
            emit(appConfig?.rotationChart ?: emptyList())
        }
    }

    override fun fetchHomeData(uniqueId: String): Flow<HomeData> = flow {
        //cache data
        HomeDataManager.getCachedHomeData(context)?.let { emit(it) }
        //remote data
        val result =
            handleNotEmptyResponse(apiServices.fetchHomeData(mapOf("uniqueId" to uniqueId).body))
        emit(result)
//        cache update
        HomeDataManager.cacheHomeData(context, result)
    }

    override fun fetchCacheHomeData(): Flow<HomeData?> = flow {
        //cache data
        emit(HomeDataManager.getCachedHomeData(context))
    }

    override fun fetchMyFavorites(pageIndex: Int) = flow {
        emit(
            handleNotEmptyResponse(
                apiServices.fetchMyFavoritesBookList(
                    mapOf(
                        "pageSize" to pageSize,
                        "pageIndex" to pageIndex,
                    ).body
                )
            ).list ?: emptyList()
        )
    }

    override fun fetchRecentlyBooks() = flow {
        val list = withContext(Dispatchers.IO) {
            dataBase.bookDao().getAll()
        }
        emit(list)
    }

    override fun addBooksHistory(book: Book) = flow {
        withContext(Dispatchers.IO) {
            dataBase.bookDao().insetAll(book)
        }
        emit(true)
    }

    override suspend fun recommendBookList(uniqueId: String, pageIndex: Int): List<Book> {
        return handleNotEmptyResponse(
            apiServices.fetchRecommendBookList(
                mapOf(
                    "pageSize" to pageSize,
                    "pageIndex" to pageIndex,
                    "uniqueId" to uniqueId,
                ).body
            )
        ).list ?: emptyList()
    }

    override suspend fun myFavorites(pageIndex: Int) = handleNotEmptyResponse(
        apiServices.fetchMyFavoritesBookList(
            mapOf(
                "pageSize" to pageSize,
                "pageIndex" to pageIndex,
            ).body
        )
    ).list ?: emptyList()

    override suspend fun mostFavorites(pageIndex: Int) = handleNotEmptyResponse(
        apiServices.fetchMostFavoritesBooks(
            mapOf(
                "pageSize" to pageSize,
                "pageIndex" to pageIndex,
            ).body
        )
    ).list ?: emptyList()
}